<?php

namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\BlackCardRule;

class BlackCardRuleController
{
    /**
     * 获取规则列表
     */
    public function list(Request $request)
    {
        $query = BlackCardRule::query();
        
        // 关键词搜索
        if ($keyword = $request->input('keyword')) {
            $query->where('name', 'like', "%{$keyword}%");
        }
        
        // 类型筛选
        if ($type = $request->input('type')) {
            $query->where('type', $type);
        }
        
        // 状态筛选
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }
        
        $list = $query->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($request->input('limit', 15));
            
        return json_success('获取成功', $list);
    }

    /**
     * 添加规则
     */
    public function add(Request $request)
    {
        $data = $request->post();
        
        $rule = new BlackCardRule();
        $rule->name = $data['name'];
        $rule->type = $data['type'];
        $rule->length = $data['length'] ?? 16;
        $rule->prefix = $data['prefix'] ?? '';
        $rule->description = $data['description'] ?? '';
        $rule->sort = $data['sort'] ?? 0;
        $rule->status = $data['status'] ?? 1;
        
        if ($rule->save()) {
            return json_success('添加成功');
        }
        return json_error('添加失败');
    }

    /**
     * 编辑规则
     */
    public function edit(Request $request, $id)
    {
        $data = $request->post();
        
        $rule = BlackCardRule::find($id);
        if (!$rule) {
            return json_error('规则不存在');
        }
        
        $rule->name = $data['name'];
        $rule->type = $data['type'];
        $rule->length = $data['length'] ?? $rule->length;
        $rule->prefix = $data['prefix'] ?? $rule->prefix;
        $rule->description = $data['description'] ?? $rule->description;
        $rule->sort = $data['sort'] ?? $rule->sort;
        $rule->status = $data['status'] ?? $rule->status;
        
        if ($rule->save()) {
            return json_success('编辑成功');
        }
        return json_error('编辑失败');
    }

    /**
     * 更新规则状态
     */
    public function updateStatus(Request $request, $id)
    {
        $status = $request->input('status');
        
        $rule = BlackCardRule::find($id);
        if (!$rule) {
            return json_error('规则不存在');
        }
        
        $rule->status = $status;
        
        if ($rule->save()) {
            return json_success('状态更新成功');
        }
        return json_error('状态更新失败');
    }
} 